package com.huiminpay.merchant.incerpt;

import com.huiminpay.merchant.common.cache.domain.BusinessException;
import com.huiminpay.merchant.common.cache.domain.CommonErrorCode;
import com.huiminpay.merchant.common.cache.domain.ErrorCode;
import com.huiminpay.merchant.common.cache.domain.RestErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//全局异常处理器（底层是利用AOP实现）
@ControllerAdvice//用ControllerAdvice(增强器)可以方便实现对Controller面向切面编程,与@Exceptionhandler配合使用实现全局异常处理
public class GlobalExceptionHandler {
    @ExceptionHandler(value=Exception.class)
    @ResponseBody //将java对象转换为json对象
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse  processException(HttpServletRequest request, HttpServletResponse res, Exception e) {
        //解析异常信息
        //判断是否为业务异常
        if(e instanceof BusinessException){
            BusinessException businessException = (BusinessException)e;
            ErrorCode errorCode = businessException.getErrcode();//获取ErrorCode对象，封装了状态码和描述信息
            int code = errorCode.getCode();
            String desc = errorCode.getDesc();
            //将code和desc封装成RestErrorResponse对象
            RestErrorResponse restErrorResponse = new RestErrorResponse(String.valueOf(code),desc);
            return restErrorResponse;
        }
        //系统异常
        CommonErrorCode unknown = CommonErrorCode.UNKNOWN;
        RestErrorResponse restErrorResponse = new RestErrorResponse(String.valueOf(unknown.getCode()),unknown.getDesc());
        return restErrorResponse;
    }
}
